package queue

import (
	"encoding/json"
	Mysql "gin/database"
	"gin/model"
	"gin/validate"
	"github.com/RichardKnop/machinery/v2/tasks"
	"gorm.io/datatypes"
)

var (
	asyncTaskMap map[string]interface{}
)

// SendMediaProcessingTask 调用点调用此异步任务函数
func SendSaveLogToQueue(requestLogs []validate.RequestLog) (err error) {
	logs, err := json.Marshal(requestLogs)
	if err != nil {
		return
	}
	args := []tasks.Arg{
		{
			Type:  "[]byte",
			Value: logs,
		},
	}
	task, err := tasks.NewSignature("save_request_log", args)
	if err != nil {
		return
	}
	task.RetryCount = 3
	_, err = AsyncTaskCenter.SendTask(task)
	return
}

// 初始化异步任务的映射map
func initAsyncTaskMap() {
	asyncTaskMap = make(map[string]interface{})
	asyncTaskMap["save_request_log"] = WriteRequestRecords
}

// WriteRequestRecords 记录RequestLog日志
func WriteRequestRecords(arg []byte) (err error) {
	Data := []validate.RequestLog{}
	err = json.Unmarshal(arg, &Data)
	if err != nil {
		return
	}
	insertData := make([]model.RequestLog, len(Data))
	for i, datum := range Data {
		req, _ := json.Marshal(datum.Request)
		insertData[i].Req = req
		insertData[i].Url = datum.Request.URL
		insertData[i].Uri = datum.Request.URI
		insertData[i].Method = datum.Request.Method
		insertData[i].StartTime = datum.StartTime
		insertData[i].Latency = datum.Latency
		insertData[i].ReqHeaders = datum.Request.Headers
		insertData[i].ReqBody = datatypes.JSON(datum.Request.Body)
		res, _ := json.Marshal(datum.Response)
		insertData[i].Res = res
		result := Mysql.DB.Create(&insertData[i])
		if result.Error != nil {
			err = result.Error
			break
		}
	}
	return err
}
